#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using namespace log_ns;

int GetSockfd() {
    int local_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (local_socket < 0) {
        LOG(FATAL, "Create socket fail\n");
        exit(0);
    }
    LOG(INFO, "Create socket success\n");
    return local_socket;
}

int main(int argc, char* args[]) {
    if (argc != 3) {
        LOG(ERROR, "please input the -> ./client、ip and port\n");
        return 0;
    }
    // 获取 ip 和 port 以及 socket
    uint16_t server_port = std::stoi(args[2]);
    std::string server_ip = args[1];

    // 绑定
    int local_socket = GetSockfd();

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    // server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

    int n = connect(local_socket, (struct sockaddr*)&server, sizeof(server));
    if (n < 0) {
        LOG(FATAL, "get sockfd fail\n");
        exit(1);
    }

    while (true) {
        std::string info;
        std::cout << "Please enter > ";
        std::getline(std::cin, info);
        // 现在将数据写入
        int n = write(local_socket, info.c_str(), info.size());
        if (n > 0) {
            char buff[1024];
            int readlen = read(local_socket, buff, sizeof(buff) - 1);
            if (readlen > 0) {
                buff[readlen] = 0;
                std::cout << buff << std::endl;
            }
        } else {
            LOG(INFO, "client quit\n");
            break;
        }
    }

    close(local_socket);

    return 0;
}